package com.blb.java12springsecutiry.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.blb.java12springsecutiry.entity.User;
import com.blb.java12springsecutiry.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author lvtian
 * @date 2023/1/31 15:32
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IUserService userService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getUsername, s));
        if(user == null) {
            throw new  UsernameNotFoundException("用户名不存在");
        }
        List<String> authList = userService.getAuthoritiesByUsername(s);
        String auths = String.join(",",authList);

        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                AuthorityUtils.commaSeparatedStringToAuthorityList(auths));
    }
}
